package com.xinnet.mms.customtransfer.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customtransfer.service.MakeOfServiceCustomService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.order.dao.OrderDao;
import com.xinnet.mms.utils.CustomerManage;
@Service("makeOfServiceCustomService")
public class MakeOfServiceCustomServiceImpl implements MakeOfServiceCustomService{
	
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private EmpCustomRelationDao empCustomRelationDao;
	@Autowired
	private CustomAllotService customAllotService;
	
	private static Logger log=LoggerFactory.getLogger(SecondDevelopCustomTransferServiceImpl.class);
	
	
	/**
	 * 根据订单生成服务期客户
	 * @throws IOException 
	 * @throws SQLException 
	 * @throws ParseException 
	 */
	public void makeOfServiceCustomer() throws IOException, SQLException, ParseException{
		String startTime ="";
		String endTime ="";
		/*String fileUrl = "";
		String filePath = this.getClass().getClassLoader().getResource("config_properties/config-orderOperate.properties").getPath();
		if("\\".equals(File.separator)){   
			fileUrl  = filePath.substring(1);
			fileUrl = fileUrl.replace("/", "\\");
		}else if("/".equals(File.separator)){   
			fileUrl  = filePath.substring(0);
			fileUrl = fileUrl.replace("\\", "/");
		}*/
		/*FileInputStream fis=new FileInputStream(fileUrl);
		Properties prop=new Properties();
        prop.load(fis);*/
        //String lastOperateOrderTime = (String)prop.get("lastOperateOrderTime");
        String lastOperateOrderTime = "";
    	SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Date currentDate = new Date();
    	endTime = sdformat.format(currentDate);
        if("".equals(lastOperateOrderTime)){
        	Calendar calendar = new GregorianCalendar();
	    	calendar.setTime(currentDate);
	    	calendar.add(calendar.DATE,-1);
	    	Date startDate=calendar.getTime(); 
	    	startTime = sdformat.format(startDate);	
        }else{
        	startTime = lastOperateOrderTime;	
        }
        List<CustomerCare> customerCareList = orderDao.getNewOrderList(startTime,endTime);
        log.info("************************************************************************************根据订单生成服务期客户流转开始********************************************");
		if(customerCareList!=null && customerCareList.size()>0){
			for (Iterator<CustomerCare> iterator = customerCareList.iterator(); iterator.hasNext();) {
				CustomerCare customerCare = (CustomerCare) iterator.next();
				makeOfServiceCustomerForEveryOne(customerCare);
			}
		}
		log.info("************************************************************************************根据订单生成服务期客户流转结束********************************************");
    	//prop.setProperty("lastOperateOrderTime",endTime);
    	//PrintStream fW = new PrintStream(new File(fileUrl));
    	/*prop.store(fW, "");
    	fW.close();
    	fis.close();*/
	}
	
	
	/**
	 * 对每个订单生成服务期客户
	 * @throws Exception 
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void makeOfServiceCustomerForEveryOne(CustomerCare customerCare){
		String productId = customerCare.getProductId();
		String customId = customerCare.getCusId();
		String productCode = customerCare.getProductCode();
		
		if(productId==null || "".equals(productId)){
			log.info("当前产品ID: is null  return");
			return;
		}
		if(productCode==null || "".equals(productCode)){
			log.info("当前产品CODE: is null  return");
			return;
		}
		if(productCode.substring(0, 1).equals("V")){
			productCode = "V";
		}
		if(productCode.substring(0, 1).equals("D")){
			productCode = "D";
		}
		if(productCode.substring(0, 1).equals("M")){
			productCode = "M";
		}
		if(productCode.indexOf("EC")!=-1){
			productCode = "CHIYUN";
		}
		if(productCode.equals("CHFW")){
			productCode = "NYZJ";
		}
		
		try {
			Customer customer = customAllotService.getCustomerById(customId);
			
			if(customer == null){
				return;
			}
			
			/*if(customer.getCustomState() != null && customer.getCustomState()==CustomerManage.ACCEPT_NO){
				return;
			}*/
			Customer paramCutom = new Customer();
			paramCutom.setProductCode(productCode);
			paramCutom.setCusId(customId);
			List<EmpCustomRelation> empCustomRelationList = empCustomRelationDao.getEmpCustomRelationByCusId(paramCutom);
			if(empCustomRelationList!=null && empCustomRelationList.size()>0){
				if(empCustomRelationList.get(0).getCustomState()==0){
					log.info("流转失败，客户未被接收，不做流转到服务期处理，customId="+customId);
					return;
				}
				//处理服务期内购买不同产品的客户流转
				List<String> productList=new ArrayList<String>();
				for(EmpCustomRelation ecr:empCustomRelationList) {
					productList.add(ecr.getProductCode());
				}
				//不包含订单中的商品进行重新分配之前要删除当前产品的关系表
				if(!productList.contains(productCode)) {
					
					customer.setProductLabel(productCode);
					customer.setProductCode(productCode);
					customer.setEmpId(empCustomRelationList.get(0).getEmpId());
					customAllotService.allot(customer, CustomerManage.SERVICE_CUSTOMER);
					return;
				}
				
				boolean isOfService = false;
				for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
					EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
					Integer customType = empCustomRelation.getCustomType();
					if(customType==CustomerManage.SERVICE_CUSTOMER){
						isOfService = true;
						break;
					}	
				}
				if(!isOfService){
					for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
						EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
						customer.setProductLabel(productId);
						customer.setEmpId(empCustomRelation.getEmpId());
						customer.setCustomerType(CustomerManage.SERVICE_CUSTOMER);
						empCustomRelation.setCustomType(CustomerManage.SERVICE_CUSTOMER);
						//empCustomRelation.setProductId(productId);
						empCustomRelation.setProductCode(productCode);
						empCustomRelation.setCustomState(CustomerManage.ACCEPT_YES);
						empCustomRelationDao.updateEmpCustomRelationById(empCustomRelation);
						customerManageDao.updateCustomType(customer);
						customerManageDao.updateCustomerProduct(customer);
					}
				}	
			}else{
				customer.setProductLabel(productCode);
				customer.setProductCode(productCode);
				customAllotService.allot(customer, CustomerManage.SERVICE_CUSTOMER);
			}
		} catch (Exception e) {
			log.error(""+e+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
	}

	public void processUnReceiveCustom(){
		//List<CustomerCare> allCustomerCareList = orderDao.getAllOrderList();
		List<EmpCustomRelation> empCustomRelationList = empCustomRelationDao.getUnReceiveCustom();
		if(empCustomRelationList!=null && empCustomRelationList.size()>0){
			for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
				EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
				processUnReceiveCustomForEveryOne(empCustomRelation);
			}
		}
	}
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void processUnReceiveCustomForEveryOne(EmpCustomRelation empCustomRelation){
		String customId = empCustomRelation.getCustomId();
		String productCode = empCustomRelation.getProductCode();
		String ecrId= empCustomRelation.getId();
		try {
			List<CustomerCare> customerCareList = orderDao.getOrdersByCusIdAndProductCode(customId, productCode);
			if(customerCareList==null || customerCareList.size()==0){
				empCustomRelationDao.delByEcrId(ecrId);
			}else{
				CustomerCare customerCare = customerCareList.get(0);
				Date tempBuyDate = customerCare.getBuyDate();
				Date tempDueDate = customerCare.getDueTime();
				empCustomRelation.setServiceStartDate(tempBuyDate);
				empCustomRelation.setServiceEndDate(tempDueDate);
				empCustomRelationDao.updateServiceDate(empCustomRelation);
			}
		} catch (Exception e) {
			// TODO: handle exception
			log.error("未接收服务期客户处理异常"+e+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
		}
	}
	
	/**
	 * 获取订单CustomerCare  List 假数据测试用
	 * @return
	 * @throws ParseException 
	 */
	private List<CustomerCare> getCustomerCareListForTest() throws ParseException{
		List<CustomerCare> customerCareList = new ArrayList<CustomerCare>();
		List<EmpCustomRelation> empCustomRelationList = null;//empCustomRelationDao.getTransferCustom();
		
		for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
			EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
			String customId = empCustomRelation.getCustomId();
			
			String productId = empCustomRelation.getProductId();
			
			CustomerCare customerCare = new CustomerCare();
			customerCare.setProductId(productId);
			customerCare.setCusId(customId);
			SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date utilBuyDate = sdf.parse("2013-05-01"); 
			java.sql.Date buyDate=new java.sql.Date (utilBuyDate.getTime());
			
			java.util.Date utilDueTime = sdf.parse("2013-05-31"); 
			java.sql.Date dueTime=new java.sql.Date (utilDueTime.getTime());

			customerCare.setBuyDate(buyDate);
			customerCare.setDueTime(dueTime);
			customerCareList.add(customerCare);
		}
		return customerCareList;
	}
	
	
	private String getRootPath(String fileName) {
		String fileUrl = "";
		String filePath = this.getClass().getClassLoader().getResource("orderOperate.properties").getPath();
		if("\\".equals(File.separator)){   
			fileUrl  = filePath.substring(1);
			fileUrl = fileUrl.replace("/", "\\");
		}else if("/".equals(File.separator)){   
			fileUrl  = filePath.substring(0);
			fileUrl = fileUrl.replace("\\", "/");
		}
		return fileUrl;
	}
	
	
	
	public static void main(String[] args) {
		
		MakeOfServiceCustomServiceImpl test  =  new MakeOfServiceCustomServiceImpl();
		String classPath = test.getRootPath("orderOperate.properties");
		
	}
}
